package net.pingfang.devicelock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.OnClose;
import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WebSocketHandler extends TextWebSocketHandler{


    private static ConcurrentHashMap<String, WebSocketSession> sessions;

    // 通过构造函数注入??
    public WebSocketHandler(ConcurrentHashMap sessions) {
        this.sessions = sessions;
    }

    // 维护 WebSocket 会话的集合（如 Map<SessionId, WebSocketSession>）

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.put(session.getId(), session);
    }


    @OnClose
    public void onClose(Session session) {
        sessions.remove(session.getId());
    }

    // 提供公共方法供外部调用（如发送消息）
    public void sendToAll(String message) {
        sessions.values().forEach(session -> {
            try {
                //判断当前会话是否为空，若为空则不发送消息
                if (session != null && session.isOpen()) {
                    session.sendMessage(new TextMessage(message));
                }else{
                    log.info("会话已经关闭");
                }
            } catch (IOException e) {
                // 处理异常
                log.error("sendToAll异常{}==>",e.getMessage());
            }
        });
    }



}

